import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    role: null
  },
  mutations: {

    ROLE (state, role) {
      state.role = role
    }
  },
  actions: {
    async login ({ commit }, loginForm) {
      const { data: res } = await axios.post('login', loginForm)
      console.log(res)
      if (res.meta.status === 200) {
        commit('ROLE', res.data.user.identity)
        window.sessionStorage.setItem('identity', res.data.user.identity)
        window.sessionStorage.setItem('token', res.data.token)
        window.sessionStorage.setItem('userId', res.data.user.id)
        window.sessionStorage.setItem('userName', res.data.user.username)
        return true
      }
      return false
    }
  },
  modules: {
  },
  getters: {
    identity (state) {
      return state.role || 2
    }
  }
})
